import pandas as pd
import numpy as np
from collections import Counter

# 加载数据集
def load_data(file_path):
    column_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']
    data = pd.read_csv(file_path, names=column_names)
    return data

# 计算欧几里得距离
def euclidean_distance(point1, point2):
    return np.sqrt(np.sum((point1 - point2) ** 2))

# KNN 分类
class KNN:
    def __init__(self, k=3):
        self.k = k
        self.X_train = None
        self.y_train = None

    def fit(self, X, y):
        self.X_train = X
        self.y_train = y

    def predict(self, X):
        predictions = []
        for x in X:
            distances = [euclidean_distance(x, x_train) for x_train in self.X_train]
            k_indices = np.argsort(distances)[:self.k]
            k_nearest_labels = [self.y_train[i] for i in k_indices]
            most_common = Counter(k_nearest_labels).most_common(1)
            predictions.append(most_common[0][0])
        return predictions

# 主程序
if __name__ == "__main__":
    # 加载数据
    data = load_data('iris/iris.data')  # 替换为你的文件路径

    # 准备训练和测试数据
    X = data.iloc[:, :-1].values  # 特征
    y = data.iloc[:, -1].values    # 标签

    # 创建 KNN 实例并训练
    knn = KNN(k=3)
    knn.fit(X, y)

    # 进行预测
    predictions = knn.predict(X)

    # 输出结果
    accuracy = np.mean(predictions == y)
    print(f'Accuracy: {accuracy * 100:.2f}%')